# -*- coding: utf-8 -*-
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI
from api.auth import router as auth_router
from api.message import router as message_router
from api.project import router as project_router
from api.logs import router as log_router
from api.pref import router as pref_router

from fastapi.middleware.cors import CORSMiddleware

from middleware.logs import RequestLoggerMiddleware
from setting import BASE_DIR
from fastapi.responses import ORJSONResponse
from prometheus_fastapi_instrumentator import Instrumentator

from database import engine
from models.user import Base
from utils.http_error import register_exception_handlers

# 创建数据库中的所有表（根据 models 中定义的表结构）
Base.metadata.create_all(bind=engine)  # 创建表，如果已存在则跳过

# 创建 FastAPI 应用实例
app = FastAPI(
    title="测试平台后端",
    description="基于FastAPI的自动化性能压测平台",
    version="1.0.0",
    default_response_class=ORJSONResponse,
    license_info={"name": "chron", "email": "chron@foxmail.com"}
)

app.mount("/media", StaticFiles(directory=BASE_DIR / "media"), name="media")

app.include_router(auth_router)
app.include_router(message_router)
app.include_router(project_router)
app.include_router(log_router)
app.include_router(pref_router)

# 加载日志中间件
app.add_middleware(RequestLoggerMiddleware)

# 设置允许的跨域来源
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许前端地址
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# 加载异常处理
register_exception_handlers(app)

# 性能监测
Instrumentator().instrument(app).expose(app)

if __name__ == "__main__":
    import uvicorn

    # uvicorn main:app --reload
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
    # uvicorn.run("main:app", host="127.0.0.1", port=8000)
